package com.smart.platform.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.smart.platform.common.wenxin.WenXinParam;
import com.smart.platform.common.wenxin.WenXinReponse;
import com.smart.platform.service.WenXinService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

@Slf4j
@Service
public class WenXinServiceImpl implements WenXinService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("#{'${wenxin.paddle-wenxin-url}'.split(',')}")
    private List<String> winXinUrlList;

    //通过AtomicLong对象实现加一计数保证线程安全问题
    private static AtomicLong paddleCount = new AtomicLong();

    @Override
    public WenXinReponse dealQuestion(String question, int valueMax,String answer) {
        //1.对flask接口的调用
        //由于在普通部署方式下，无法利用cpu多核，因此其中一种解决方法是部署多个实例
        //Count加一后，对UrlList长度取余，以轮询每个的实例。实现简单的负载均衡，调用多个实例
        int index = (int)(paddleCount.incrementAndGet()%winXinUrlList.size());
        String WinXinResult = restTemplate.postForObject(winXinUrlList.get(index),new WenXinParam(question,valueMax,answer),String.class);
        //2.接收并处理返回值

        JSONObject wenXinResultJsonObject = JSONObject.parseObject(WinXinResult);
        String WinXinStr = wenXinResultJsonObject.getString("data");

        WenXinReponse wenXinReponse = new WenXinReponse(WinXinStr);
        return wenXinReponse;
    }


}
